//
//  QianliUniversalFunc.swift
//  todoios
//
//  Created by qianli on 2025/4/10.
//


import UIKit

class QianliUniversalFunc:NSObject{
//单例初始化方法1：
    static let sharedInstance = QianliUniversalFunc() //单例
    
    private override init(){
        super.init()
    }
    
}

extension QianliUniversalFunc{
    class func kEXRWXI8p2baadf8(_ smallNumber: CGFloat, and bigNumber: CGFloat) -> Float {
        let diff = bigNumber - smallNumber
        return Float((CGFloat(arc4random()) / 100.0).truncatingRemainder(dividingBy: diff) + smallNumber)
    }
    
    class func B6NlI6IEEQDFXLK3(_ schemeurl:String,_ completeblock: ((_ success:Bool)->Void)?){
        if 0 == schemeurl.count{
            if completeblock != nil{
                completeblock?(false)
            }
            return
        }
        if schemeurl.contains("://") || schemeurl.hasPrefix("App-Prefs:"){//urlscheme及设置
            PqHXCLMrbGaK2xN1(schemeurl, completeblock)
        }else{
            let flag = fjvBR3fUEWlnWpkp(schemeurl)
            if !flag {
                PqHXCLMrbGaK2xN1(schemeurl, completeblock)
            }else if completeblock != nil{
                completeblock?(flag)
            }
        }
    }

    class func PqHXCLMrbGaK2xN1(_ schemeurl:String,_ completeblock: ((_ success:Bool)->Void)?){
        if let url = NSURL(string: schemeurl){
            UIApplication.shared.open(url as URL,options: [:]) { success in
                if success {
                    if completeblock != nil{
                        completeblock?(true)
                    }
                }else{
                    NSLog("打开取消或失败:\(schemeurl)")
                    if completeblock != nil{
                        completeblock?(false)
                    }
                }
            }
        }
    }

    class func fjvBR3fUEWlnWpkp(_ bundleID:String) -> Bool{
        if bundleID.isEmpty{
            return false
        }
        let clstr = "TFNBcHBsaWNhdGlvbldvcmtzcGFjZQ".qianli_safe_base64_decode()
        let prostr = "b3BlbkFwcGxpY2F0aW9uV2l0aEJ1bmRsZUlEOg".qianli_safe_base64_decode()
        if clstr != nil && prostr != nil{
            return false
        }else{
            return false
        }
    }
    
    class func igGP6m72nfSVVUFI(forName name: String) -> Array<String> {
        if name.isEmpty{
            return []
        }
       do {
          if let bundlePath = Bundle.main.path(forResource: name, ofType: "json"),
          let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
             if let json = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as? [String] {
                 return json
             } else {
                print("Given JSON is not a valid dictionary object.")
             }
          }
       } catch {
          print(error)
       }
        return []
    }
    
// debug下日志打印封装
    class func QianliLog<T>(_ message : T) {
        #if DEBUG
            print("\(message)")
        #endif
    }
    
    class func QianliLogLine<T>(message : T, file : String = #file, lineNumber : Int = #line) {
        #if DEBUG
            let fileName = (file as NSString).lastPathComponent
            print("[\(fileName)<\(lineNumber)>]- \(message)")
        #endif
    }
    
}

extension QianliUniversalFunc{
    func n5WQUmE02guLNnEz()-> Float {    // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        //缓存目录路径 "/var/mobile/Containers/Data/Application/xxx/Library/Caches"
        //取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        var size = 0
        for file in fileArr! {
            let path = cachePath?.appending("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path!)
            // 用元组取出文件大小属性
            for (abc, bcd) in floder {
                // 累加文件大小
                if abc == FileAttributeKey.size {
                    size += (bcd as AnyObject).integerValue
                }
            }
        }
        let mm = Double(size) / 1000.0 / 1000.0
        return Float(mm)
    }
    
    func DGWKlfi5iEfwXMR8()->Float{
        let userDefaults = UserDefaults.standard
        let dics = userDefaults.dictionaryRepresentation()
        var result = 0.0
        for key in dics {
            let keyName = key.key //包含系统为App配置的一些默认参数，故只需删除自身需要删除的即可
            print("calc.key:\(key.key)")
            if keyName.hasPrefix("qianli.default.") || keyName.hasPrefix("qianli.standard."){
                if let data = key.value as? Data{
                    let iSize = Double(data.count) / 1000000.0
                    result = result + iSize
                    print("calc.size: \(iSize)M")
                }
            }
        }//清除所有可能的图片缓存(所有可以清除的缓存(如图片缓存)等都以aiScreen.开头)
        return Float(result)
    }
    
    func WcxBmuI34ZOz3Sd6()->Float{
        let cachSize = n5WQUmE02guLNnEz()
        let userSize = DGWKlfi5iEfwXMR8()
        return cachSize + userSize
    }
    
    func CauZiEw2TyXy7F2H() {
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        for file in fileArr! {
            let path = cachePath?.appending("/\(file)")
            if FileManager.default.fileExists(atPath: path!) {
                do {
                try FileManager.default.removeItem(atPath: path!)
                }
                catch {
                    print("clearCache.err")
                }
            }
        }
    }
    
    func JIBF4g9XvehXwPX8(deepClean:Bool=false){
       let userDefaults = UserDefaults.standard
       let dics = userDefaults.dictionaryRepresentation()
       for key in dics {
           let keyName = key.key //包含系统为App配置的一些默认参数，故只需删除自身需要删除的即可
           if keyName.hasPrefix("qianli.default.") || keyName.hasPrefix("qianli.standard."){
               print("remove.key:\(key.key)")
               userDefaults.removeObject(forKey: key.key)
           }
       }
       userDefaults.synchronize()
    }
    
    func Tju6icGvNKLcvCiG(deepClean:Bool=false){
        CauZiEw2TyXy7F2H()
        JIBF4g9XvehXwPX8(deepClean: deepClean)
    }
}

